<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import API from '@/services';
import AQueryHeader, { useQueryHeader } from '@dangojs/a-query-header';
import AQueryTable from '@dangojs/a-query-table';

import { Message, Modal } from '@arco-design/web-vue';
import Select from '@/arco-components/select/index.vue';
import { useRouter } from 'vue-router';

import CreateEditDrawer from '../createEditDrawer/index.vue'
import ArcoCustomColumn from '@/arco-components/arcoCustomColumn/index'
import CheckApprovalDrawer from '@/views/approvalCenter/components/checkDrawer.vue'
import {approvalStatus, statusColor} from '@/constants/approvalCenter'
import { ECustomColumn } from '@/utils/constants';
import _ from 'lodash'

import * as RouteNames from '@/router/consts';

const router = useRouter();
const emit = defineEmits(['onSuccess'])
interface FormDataI {
  demandName: string | undefined;
  demandType: string | undefined;
  id: string | undefined;
  status: string | undefined;
}

const formData = reactive<FormDataI>({
  demandName: undefined,
  demandType: undefined,
  id: undefined,
  status: undefined,
});

const querytableRef = ref<any>(null);
const loading = ref<boolean>(false)
const checkDraweRef = ref()
const createDrawerRef = ref()
//自定义列
const settings: any = ref([]);
//表格展示的字段
const newTableColumn: any = ref([]);
// 状态
const statusData: any = ref([]);
// 需求类型
const demandTypeData: any = ref([]);

// 创建时详情页面
const detailPageData:any = ref()

// 编辑的数据
const editData:any = ref()

// 获取需求状态下拉数据
const getDemandStatusEnum = async () => {
  try {
    const { code, data } = await API.enumBao.getDemandStatusEnum({
      // type: EindexType.ATOMIC
    });
    if (code === 200 && Array.isArray(data)) {
      statusData.value = data?.map(
        (item:any) => {
          return {
            label: item.value,
            value: item.key
          }
        }
      );
    }
  } catch (error) {
    console.log(error);
  }
};

// 获取需求类型下拉数据
const getDemandTypeEnum = async () => {
  try {
    const { code, data } = await API.enumBao.getDemandTypeEnum({
      // type: EindexType.ATOMIC
    });
    if (code === 200 && Array.isArray(data)) {
      demandTypeData.value = data.map((item=> {
        return {
          label: item.value,
          value: item.key
        }
      }));
    }
  } catch (error) {
    console.log(error);
  }
};
const sleep = (wait:any) => new Promise((resolve) => setTimeout(resolve,wait))
const createEditDrawerRef :any = ref()
const requestData = async (query: any) => {
  loading.value = true
  try {
    const res = await API.demand.postQueryPage(query);
    loading.value = false
    if (res.data) {
      return {
        success: true,
        data: res.data.list,
        total: Number(res.data.total)
      };
    }
    return {
      success: true,
      data: [],
      total: 0
    };
  } catch (e) {}
};
const { onReset,onSubmit, params } = useQueryHeader(formData, false);

// 编辑态时获取数据
const editApi = async (id:any) => {
  try {
    const res = await API.demand.getGetById({
      id
    });
    return res
  } catch (error) {
    console.warn(error);
  }
}
const onEdit = async (id:any) => {
  const res = await editApi(id)
  if (res?.code === 200) {
    editData.value = res.data;
    createEditDrawerRef.value.visibleFn()
  }
}
const onCheck = (row: any) => {   
    getCheckDetail(row)
}
// 查看(分为指标类型为创建的需求 和 指标定义/下线/发布/删除”)
const getCheckDetail = async (row: any) => {
  
  if (row.demandType === 'DEMAND') {
    const res = await editApi(row.id)
    if (res?.code === 200) {
      editData.value = res.data;
      checkDraweRef.value.visibleFn()
    }
  } else {
    try {
      router.push({
        name: RouteNames.ROUTER_APPROVAL_CENTER.CheckDetail,
        params: {
          id: row.id
        }
      })
      
    } catch (error) {
      console.warn(error);
    }
  }
};
// 删除
const onDelete = (id: any) => {
  Modal.confirm({
    modalClass: 'model-message-confirm',
    title: '是否确定删除此审批？',
    content: '删除后不可恢复',
    simple: false,
    closable: true,
    okText: '确认删除',
    okButtonProps: {
      style: {
        backgroundColor: '#FF1A3B'
      }
    },
    onBeforeOk: (done) => {
      fetchDelete(id)
        .then((res: any) => {
          if (res.code === 200) {
            Message.success('删除成功');
            // todo: 当前页最后一条怎么办;ps:用removeReload替代reload
            querytableRef.value.removeReload();
          }
        })
        .finally(() => {
          done(true);
        });
    }
  });
};
const fetchDelete = async (id: any) => {
  try {
    const res = await API.demand.deleteDeleteById({ id });
    // todo: API接口出错不会出现异常
    return res;
  } catch (error) {
    throw error;
  }
};
/* table Column */
const tableColumn = ref([
  {
    title: "状态",
    dataIndex: "status",
    slotRenderName: 'status',
    keys: 7,
  },
  {
    title: "操作",
    dataIndex: "operator",
    width: 200,
    keys: 8,
    slotRenderName: 'operator',
    fixed: 'right',
  }
])

/* 获取自定义列列表 */
const getCustomColumnApi = async () => {
  try {
    const { code, data }: any = await API.userPageSetting.getFindOne({
      pageCode: ECustomColumn?.created
    });
    if (code === 200) {
      settings.value = data?.settings.map((item:any) => {
        return {
          ...item,
          title: item.label,
          dataIndex: item.prop,
        }
      });

      // 判断表头列是否都选中
      // const checkAllColumn = settings.value.filter((s:any) => !s.isCheck)
      const column = settings.value?.map((v: any, i: number) => {
        const columnIndex = tableColumn.value?.findIndex(
          (val: any) => val?.keys === v?.keys
        );
        let columnExtraParams :any = {
          ellipsis: true,
          tooltip: true,
        }

        if (v.keys === 3 || v.keys === 5) {
          Object.assign(v, columnExtraParams)
        }
        if (v.keys === 1) {
          v.width = 100
        }
        return {
          ...tableColumn.value[columnIndex],
          ...v,
          columnKey: Date.now()
        };
      });
      
      newTableColumn.value = _.compact(column);
      newTableColumn.value = newTableColumn.value.filter((v: any) => v.isCheck)
    }
  } catch (error) {
    console.log(error);
  }
};

/* 保存自定义列表 */
const customColumnConfirm = async (vo: any) => {
  try {
    const { code } = await API.userPageSetting.postSave({
      pageCode: ECustomColumn?.created,
      settings: vo?.map(({ disabled, keys, isCheck, label, prop }: any) => {
        return {
          disabled,
          keys,
          isCheck,
          label,
          prop
        };
      })
    });
    if (code === 200) {
      Message.success('保存配置成功');
      getCustomColumnApi();
    }
  } catch (error) {
    console.log(error);
  }
};
const handleSuccessResult = () => {
  querytableRef.value.reload();
  
}
const handleSuccess = () => {
  querytableRef.value.reload();
}
onMounted(() => {
  getDemandStatusEnum(); // 需求类型下拉数据
  getDemandTypeEnum(); // 状态下拉数据
  getCustomColumnApi(); // 表格头数据
});
defineExpose({
  handleSuccessResult
})
</script>
 <!-- @autoSubmit="onAutoSubmit" -->
<template>
  <div>
    <div class="filter-search">
      <AQueryHeader @reset="onReset" @submit="onSubmit" :num="5">
        <AFormItem show-colon label="需求ID">
          <AInput  v-model="formData.id" placeholder="请输入" />
        </AFormItem>
        <AFormItem show-colon label="审批类型">
          <Select  v-model="formData.demandType" :options="demandTypeData" placeholder="请选择"></Select>
        </AFormItem>
        <AFormItem show-colon label="需求名称">
          <AInput  v-model="formData.demandName" placeholder="请输入" />
        </AFormItem>
        <AFormItem show-colon label="状态">
          <Select  v-model="formData.status" :options="statusData" placeholder="请选择"></Select>
        </AFormItem>
      </AQueryHeader>
    </div>
    <a-divider />
    <div class="table-operate">
      <div class="CustomColumn-operate-wrap">
        <ArcoCustomColumn
          @confirm="(v: any) => customColumnConfirm(v)"
          :tableColumn="settings"
        />
      </div>
    </div>
    <AQueryTable
      ref="querytableRef"
      :columns="newTableColumn"
      :request="requestData"
      :params="params"
      :loading="loading"
      class="p-18"
    >
      <template #status="{ record }">
        <span :class="['dot', statusColor[record.status+'']]"></span>
        <span>{{record.statusDesc}}</span>
      </template>
      <template #operator="{ record }">
        <a-button 
           type="text" 
          :disabled="record.status != 10" 
          @click="() => onEdit(record?.id)">
          编辑
        </a-button>
        <a-divider direction="vertical" />
        <a-button 
          type="text" 
          :disabled="
            record.status === 20 || record.status === 30 ||
            record.status === '20' || record.status === '30'
          "
          @click="() => onDelete(record?.id)">
          删除
        </a-button>
        <a-divider direction="vertical" />
        <a-button 
          type="text"
          @click="() => onCheck(record)">
          查看
        </a-button>
      </template>
    </AQueryTable>
  </div>
  
  <CreateEditDrawer 
    :editData="editData"
    title="编辑需求"
    ref="createEditDrawerRef"
    @editSuccess="handleSuccess"
  />
  <CheckApprovalDrawer
   :checkDetail="editData"
   ref="checkDraweRef" />
  
</template>
<style lang="scss" scoped>
@import './index.scss';
</style>
